import React, { FunctionComponent, useState } from 'react';
import { Button, Card, Message } from '@alifd/next';
import styles from './index.module.scss';
import { useInterval } from './utils';

export interface ExceptionProps {
  statusCode: string;
  description: string;
  image: string;
  buttonBackDesc?: string;
  buttonContinueDesc?: string;
  countDownSecnods?: number;
  onButtonBack?: () => any;
  onButtonContinue?: () => any;
}

const Result: FunctionComponent<ExceptionProps> = (props: ExceptionProps) => {
  const {
    statusCode,
    description,
    image,
    buttonBackDesc,
    buttonContinueDesc,
    countDownSecnods = 0,
    onButtonBack,
    onButtonContinue,
  } = props;

  const [second, setSecond] = useState(countDownSecnods);

  const gobackHandle = () => {
    if (onButtonBack) {
      onButtonBack();
    } else {
      Message.notice('返回修改');
    }
  };

  useInterval(
    () => {
      setSecond(second - 1);
      if (second <= 1) {
        gobackHandle();
      }
    },
    second > 0 ? 1000 : null,
  );

  const goContinueHandle = () => {
    if (onButtonContinue) {
      onButtonContinue();
    } else {
      Message.notice('继续创建函数响应');
    }
  };

  return (
    <Card free className={styles.exception}>
      <div>
        <img src={image} className={styles.exceptionImage} alt="img" />
        <h1 className={styles.statuscode}>{statusCode}</h1>
        <div className={styles.description}>{`${second >= 0 && countDownSecnods ? second : ''}${description}`}</div>
        <div className={styles.operationWrap}>
          {buttonBackDesc && (
            <Button type="primary" onClick={gobackHandle} className={styles.mainAction}>
              {buttonBackDesc}
            </Button>
          )}
          {buttonContinueDesc && <Button onClick={goContinueHandle}>{buttonContinueDesc}</Button>}
        </div>
      </div>
    </Card>
  );
};

export default Result;
